package me.yangzhi.day_15;

import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

import java.nio.charset.StandardCharsets;
import java.util.List;

import me.yangzhi.day_15.model.Movie;
import me.yangzhi.day_15.model.MovieResponse;

public class GsonDemo extends AppCompatActivity {
    private static final String TAG = "GsonDemo";
    private TextView serializationResultTextView;
    private ListView moviesListView;
    private RequestQueue requestQueue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gson_demo);
        
        serializationResultTextView = findViewById(R.id.serializationResultTextView);
        moviesListView = findViewById(R.id.moviesListView);
        
        // 初始化Volley请求队列
        requestQueue = Volley.newRequestQueue(this);
        
        // 演示序列化
        demonstrateSerialization();
        
        // 演示反序列化 (使用 Volley)
        demonstrateDeserializationWithVolley();
    }

    private void demonstrateSerialization() {
        // 创建一个Movie对象
        Movie movie = new Movie();
        movie.setId(1);
        movie.setTitle("The Shawshank Redemption");
        movie.setDirector("Frank Darabont");
        movie.setYear(1994);
        movie.setRating(9.3);
        movie.setPoster("shawshank.jpg");

        // 使用Gson进行序列化
        Gson gson = new Gson();
        String json = gson.toJson(movie);
        
        Log.d(TAG, "Serialized JSON: " + json);
        serializationResultTextView.append(json + "\n\n");
    }

    private void demonstrateDeserializationWithVolley() {
        // 建议使用10.0.2.2，如果使用的是真实设备，请替换为电脑的局域网IP
        String url = "http://10.0.2.2:8080/movies/img/movies_list_data.json";

        // 创建自定义的StringRequest，重写parseNetworkResponse处理UTF-8编码
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            response -> {
                // 处理响应
                Log.d(TAG, "Volley Response: " + response);
                
                try {
                    // 使用Gson进行反序列化，先反序列化为MovieResponse对象
                    Gson gson = new Gson();
                    MovieResponse movieResponse = gson.fromJson(response, MovieResponse.class);
                    
                    // 从MovieResponse对象中获取电影列表
                    List<Movie> movies = movieResponse != null ? movieResponse.getData() : null;

                    // 更新ListView
                    if (movies != null && !movies.isEmpty()) {
                        // 创建ArrayAdapter
                        MovieAdapter adapter = new MovieAdapter(this,
                                R.layout.list_item_movie, movies);
                        // 设置Adapter给ListView
                        moviesListView.setAdapter(adapter);
                    } else {
                        // 如果列表为空，可以在日志中记录或更新一个提示TextView
                        Log.d(TAG, "反序列化结果为空或列表为空");
                        // 例如，清空ListView或显示一个空视图
                        moviesListView.setAdapter(null);
                    }
                
                } catch (JsonSyntaxException e) {
                    Log.e(TAG, "Gson JsonSyntaxException during deserialization", e);
                    // 在UI线程更新TextView显示错误信息
                    runOnUiThread(() -> serializationResultTextView.append("\n反序列化错误 (JsonSyntaxException)：" + e.getMessage()));
                } catch (Exception e) {
                    Log.e(TAG, "Other Error during deserialization", e);
                    // 在UI线程更新TextView显示错误信息
                     runOnUiThread(() -> serializationResultTextView.append("\n反序列化错误 (其他)：" + e.getMessage()));
                }
                
            },
            error -> {
                // 处理错误
                Log.e(TAG, "Volley Error during deserialization", error);
                // 在UI线程更新TextView显示错误信息
                runOnUiThread(() -> serializationResultTextView.append("\n反序列化错误 (Volley)：" + error.getMessage()));
            }) {
            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String parsed;
                try {
                    // 强制使用UTF-8解码响应体
                    parsed = new String(response.data, StandardCharsets.UTF_8);
                } catch (Exception e) {
                    // 如果解码失败，回退到默认处理方式
                    parsed = new String(response.data);
                }
                return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
            }
        };

        // 将请求添加到请求队列
        requestQueue.add(stringRequest);
    }
} 